<script lang="ts" setup>
import _ from 'lodash';
import { tryit } from 'radash';
import { FormInstanceFunctions, MessagePlugin } from 'tdesign-vue-next';
import { ref } from 'vue';
import mockApi from '@/api/mock';
import { PostData, ResultItem } from '@/api/model/mockModel';
import { SUCCESS_CODE } from '@/constants';
import { FORM_RULES, list, INIT_DATA } from './data/FTP';
import { useLoading } from '@/hooks/useLoading';

const containerRef = ref<HTMLDivElement>();
const formRef = ref<FormInstanceFunctions>();
const { loadingStart, loadingEnd } = useLoading(containerRef);
const formData = ref({ ...INIT_DATA });
const detailData = ref<ResultItem>();

const handelSubmit = async () => {
  const validateRes = await formRef.value.validate();

  if (validateRes === true) {
    loadingStart();

    const postData: PostData = { ...formData.value };
    const id = detailData.value?.id;
    const api = id ? mockApi.update : mockApi.create;

    if (id) postData.id = id;

    const [err, res] = await tryit(api)(postData);

    if (!err && res.code === SUCCESS_CODE) {
      await MessagePlugin.success('操作成功');
    }

    loadingEnd();
  }
};
</script>

<template>
  <div class="FTP-wrap">
    <t-form ref="formRef" :rules="FORM_RULES" :data="formData" :colon="true" :label-width="100" label-align="left">
      <div class="common-item-view">
        <t-row :gutter="[0, 20]">
          <t-col v-for="(item, index) in list" :key="index" :span="index === 0 ? 12 : 6">
            <div class="item">
              <form-item :form-data="formData" :data="item"> </form-item>
            </div>
          </t-col>
        </t-row>
      </div>
    </t-form>
    <div class="btm-btn-box">
      <t-button class="btm-btn" theme="primary" @click="handelSubmit">保存</t-button>
    </div>
  </div>
</template>

<style lang="less" scoped>
.FTP-wrap {
  padding-top: 10px;
  .item {
    :deep(.t-form__label) {
      width: 120px !important;
      text-align: end;
      margin-right: 13px;
      padding-right: 0 !important;

      label {
        font-size: 12px !important;
        text-align: end;
      }
    }
    :deep(.t-form__controls-content) {
      width: 230px !important;
    }
  }
  .btm-btn-box {
    display: flex;
    justify-content: center;
    .btm-btn {
      width: 80px;
      height: 32px;
    }
  }
}
</style>
